package com.sfx.concurrent.demo.线程基础.线程的创建;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

@Slf4j(topic = "c.TestThread6")
public class TestThread6 {
    private static boolean flg = false;

//    @SneakyThrows
//    public static void main(String[] args) {
//        Thread thread = new Thread(() -> {
//            while (!flg) {
//                log.debug("进入while()....");
//            }
//            log.debug("退出....");
//        });
//        thread.start();
//        Thread.sleep(10);
//        log.debug("flg = true");
//        flg = true;
//    }
//    public static void main(String[] args) {
//        Thread t = new Thread(() -> {
//            while(!Thread.currentThread().isInterrupted()) {
//                log.debug("没有被打断");
//            }
//            log.debug("被打断");
//        },"t1线程");
//
//        t.start();
//
//        try {
//            Thread.sleep(1000);
//            log.debug("打标记");
//            t.interrupt();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//    }

    public static void main1(String[] args) throws InterruptedException {
        Thread t = new Thread(() -> {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    log.debug("退出");
                    break;
                }
                try {
                    Thread.sleep(1000);
                    log.debug("1111");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();//启动t线程
        Thread.sleep(1000);
        t.interrupt();
        log.debug("打断标记 + " + t.isInterrupted());
    }

    private Thread monitor;

    public static void main(String[] args) throws InterruptedException {
        TestThread6 t = new TestThread6();
        t.start();
        Thread.sleep(3500);
        t.stop();
    }

    public void start() {
        monitor = new Thread(() -> {
            while (true) {
                // 1. 先要判断有没有被打断
                if (Thread.currentThread().isInterrupted()) {
                    // 不会清除打断标记

                    log.debug("被打断,立即退出");
                    return;
                }
                // 2. 如果没有被打断,先睡眠1s
                try {
                    Thread.sleep(1000);
                    log.debug("执行监控记录");
                } catch (InterruptedException e) {
                    log.debug("睡眠的时候被打断");
                    e.printStackTrace();
                    // 如果有打断异常,打断正在sleep,join,wait方法会清除标记,我们需要重新设置标记
                    monitor.interrupt();
                }
            }
        },"monitor");
        monitor.start();
    }

    public void stop() {
        monitor.interrupt();
    }
}